package com.zmn.brs.admin.controller.rule.engineer;

import com.alibaba.fastjson.JSONObject;
import com.zmn.brs.admin.controller.rule.base.AlarmRuleBaseController;
import com.zmn.brs.business.interfaces.rule.AlarmRuleBService;
import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.common.enums.EventTypeEnum;
import com.zmn.brs.common.enums.ExpressionEnum;
import com.zmn.brs.common.enums.ThresholdExpressionEnum;
import com.zmn.brs.dubbo.constant.DubboConsts;
import com.zmn.brs.model.entity.threshold.Threshold;
import com.zmn.brs.model.query.rule.EngineerRuleCustomQuery;
import com.zmn.brs.model.query.rule.OrderRuleCustomQuery;
import com.zmn.brs.model.vo.rule.ComparisonRuleVO;
import com.zmn.brs.model.vo.rule.QuantityRuleVO;
import com.zmn.brs.model.vo.rule.SalesRuleVO;
import com.zmn.brs.model.vo.rule.UnpaidRuleVO;
import com.zmn.brs.services.interfaces.threshold.ThresholdService;
import com.zmn.brs.utils.BrsUtil;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.plat.common.dictionary.StatusEnum;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 描述： 工程师指标规则
 *
 * @author chongw
 * @since 2021-07-02 17:05:29
 */
@RestController
@RequestMapping("/brs/engineer/rule/")
public class EngineerRuleModifyController extends AlarmRuleBaseController {

    @Resource
    private AlarmRuleBService alarmRuleBService;

    @Resource
    private ThresholdService thresholdService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private StaffListRemoteService staffListRemoteService;

    /**
     * 保存收款未支付金额规则配置
     *
     * @param unpaidRuleVO
     * @return
     */
    @ResponseBody
    @RequestMapping("unpaid/addEdit")
    public ResponseDTO addEditComparison(@RequestBody UnpaidRuleVO unpaidRuleVO) {
        try {
            Date now = DateUtil.getNow();
            if (NumberUtil.isNullOrZero(unpaidRuleVO.getEventId())) {
                return ResponseDTO.fail("参数不能为空");
            }
            if (unpaidRuleVO.getValue() == null) {
                return ResponseDTO.fail("收款未支付金额阈值不能为空");
            }
            if (unpaidRuleVO.getValue() < 0) {
                return ResponseDTO.fail("收款未支付金额阈值必须大于等于0");
            }
            if (NumberUtil.isNullOrZero(unpaidRuleVO.getPlat())) {
                return ResponseDTO.fail("平台不能为空");
            }
            if (NumberUtil.isNullOrZero(unpaidRuleVO.getOrgThrId())) {
                return ResponseDTO.fail("子公司不能为空");
            }
            /*if (NumberUtil.isNullOrZero(unpaidRuleVO.getReceiverId())) {
                return ResponseDTO.fail("钉钉接收人不能为空");
            }*/
            if (NumberUtil.isNullOrZero(unpaidRuleVO.getRobotId())) {
                return ResponseDTO.fail("钉钉群不能为空，请选择钉钉群！");
            }
            /*//查询接收人姓名
            ResponseDTO<StaffDRO> responseDTO = staffListRemoteService.getStaff(unpaidRuleVO.getReceiverId());
            if (responseDTO.getData() == null) {
                return ResponseDTO.fail("未找到钉钉接收人信息");
            }
            StaffDRO staffDRO = Optional.ofNullable(responseDTO.getData()).orElse(new StaffDRO());
            unpaidRuleVO.setReceiverName(staffDRO.getRealName());*/

            //查询规则ID
            Integer ruleId = alarmRuleBService.findRuleIdByEventId(unpaidRuleVO.getEventId());
            if (ruleId == null) {
                return ResponseDTO.fail("无规则配置数据");
            }
            unpaidRuleVO.setRuleId(ruleId);
            unpaidRuleVO.setExpression(ExpressionEnum.GT.getExpression());

            //获取唯一key
            String uniqueNo = RedisKeyConst.getCacheRuleConfigRedisKey(EventTypeEnum.ENGINEER_UNPAID.getTypeId(), unpaidRuleVO.getOrgThrId());
            unpaidRuleVO.setUniqueNo(uniqueNo);

            //判断是否存在
            Integer count = alarmRuleBService.countRuleExistByQuery(EngineerRuleCustomQuery.builder()
                    .thresholdId(unpaidRuleVO.getThresholdId())
                    .uniqueNo(uniqueNo)
                    .build());
            if (count > 0) {
                return ResponseDTO.fail(String.format("已存在【%s】收款未支付金额配置！！", unpaidRuleVO.getOrgThrName()));
            }

            AtomicReference<Integer> flag = new AtomicReference<>(0);
            //新增
            if (NumberUtil.isNullOrZero(unpaidRuleVO.getThresholdId())) {
                //阈值
                Threshold threshold = Threshold.builder()
                        .ruleId(unpaidRuleVO.getRuleId())
                        .thresholdId(unpaidRuleVO.getThresholdId())
                        .thresholdName(String.format("%s-收款未支付金额阈值", unpaidRuleVO.getOrgThrName()))
                        .type(0)
                        .thresholdParam(String.valueOf(unpaidRuleVO.getEventId()))
                        .thresholdValue(JSONObject.toJSONString(unpaidRuleVO))
                        .expression(ThresholdExpressionEnum.ALL.getExpression())
                        .creater(super.getMcStaffRealName())
                        .updater(super.getMcStaffRealName())
                        .updateTime(now)
                        .createTime(now)
                        .build();
                flag.updateAndGet(v -> v + thresholdService.insert(threshold));

                if (flag.get() > 0) {
                    alarmRuleBService.cacheRule(uniqueNo, unpaidRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            //修改
            else {

                Threshold threshold = thresholdService.findById(unpaidRuleVO.getThresholdId());
                UnpaidRuleVO vo = JSONObject.parseObject(threshold.getThresholdValue(), UnpaidRuleVO.class);
                //获取上次rediskey
                String oldRedisKey = vo.getUniqueNo();

                vo.setOrgThrId(unpaidRuleVO.getOrgThrId());
                vo.setOrgThrName(unpaidRuleVO.getOrgThrName());
                vo.setPlat(unpaidRuleVO.getPlat());
                vo.setPlatName(unpaidRuleVO.getPlatName());
                vo.setExpression(unpaidRuleVO.getExpression());
                vo.setValue(unpaidRuleVO.getValue());
                vo.setReceiverId(unpaidRuleVO.getReceiverId());
                vo.setReceiverName(unpaidRuleVO.getReceiverName());
                //添加钉钉群支持
                vo.setRobotId(unpaidRuleVO.getRobotId());
                vo.setGroupName(unpaidRuleVO.getGroupName());
                threshold.setThresholdName(String.format("%s-收款未支付金额阈值", unpaidRuleVO.getOrgThrName()));
                threshold.setThresholdValue(JSONObject.toJSONString(vo));
                threshold.setUpdateTime(now);
                threshold.setUpdater(super.getMcStaffRealName());

                flag.updateAndGet(v -> v + thresholdService.updateByKey(threshold));

                if (flag.get() > 0) {
                    alarmRuleBService.cacheRule(uniqueNo, oldRedisKey, unpaidRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            if (flag.get() > 0) {
                return ResponseDTO.success();
            }
        } catch (Exception e) {
            logger.error("保存收款未支付金额规则配置异常，异常信息：" + e);
            e.printStackTrace();
        }
        return ResponseDTO.fail("保存收款未支付金额规则配置失败");
    }

    /**
     * 保存派单客单价规则配置
     *
     * @param salesRuleVO
     * @return
     */
    @ResponseBody
    @RequestMapping("sales/addEdit")
    public ResponseDTO addEditQuantity(@RequestBody SalesRuleVO salesRuleVO) {
        try {
            Date now = DateUtil.getNow();
            if (NumberUtil.isNullOrZero(salesRuleVO.getEventId())) {
                return ResponseDTO.fail("参数不能为空");
            }
            if (StringUtil.isBlank(salesRuleVO.getExpression())) {
                return ResponseDTO.fail("派单客单价比较符不能为空");
            }
            if (!NumberUtil.isPositiveDouble(salesRuleVO.getValue())) {
                return ResponseDTO.fail("派单客单价阈值必须大于0");
            }
            if (NumberUtil.isNullOrZero(salesRuleVO.getPlat())) {
                return ResponseDTO.fail("平台不能为空");
            }
            if (NumberUtil.isNullOrZero(salesRuleVO.getOrgThrId())) {
                return ResponseDTO.fail("子公司不能为空");
            }
            /*if (NumberUtil.isNullOrZero(salesRuleVO.getReceiverId())) {
                return ResponseDTO.fail("钉钉接收人不能为空");
            }*/
            if (NumberUtil.isNullOrZero(salesRuleVO.getRobotId())) {
                return ResponseDTO.fail("钉钉群不能为空，请选择钉钉群！");
            }
            //查询接收人姓名
            /*ResponseDTO<StaffDRO> responseDTO = staffListRemoteService.getStaff(salesRuleVO.getReceiverId());
            if (responseDTO.getData() == null) {
                return ResponseDTO.fail("未找到钉钉接收人信息");
            }
            StaffDRO staffDRO = Optional.ofNullable(responseDTO.getData()).orElse(new StaffDRO());
            salesRuleVO.setReceiverName(staffDRO.getRealName());*/

            //查询规则ID
            Integer ruleId = alarmRuleBService.findRuleIdByEventId(salesRuleVO.getEventId());
            if (ruleId == null) {
                return ResponseDTO.fail("无规则配置数据");
            }
            salesRuleVO.setRuleId(ruleId);
            //获取唯一key
            String uniqueNo = RedisKeyConst.getCacheRuleConfigRedisKey(EventTypeEnum.ENGINEER_SALES.getTypeId(), salesRuleVO.getOrgThrId(),
                    ExpressionEnum.getExpressionEnum(salesRuleVO.getExpression()).name().toLowerCase()
            );
            salesRuleVO.setUniqueNo(uniqueNo);

            //判断是否存在
            Integer count = alarmRuleBService.countRuleExistByQuery(EngineerRuleCustomQuery.builder()
                    .thresholdId(salesRuleVO.getThresholdId())
                    .uniqueNo(uniqueNo)
                    .build());
            if (count > 0) {
                return ResponseDTO.fail(String.format("已存在【%s】派单客单价配置！！", salesRuleVO.getOrgThrName()));
            }
            AtomicReference<Integer> flag = new AtomicReference<>(0);
            //新增
            if (NumberUtil.isNullOrZero(salesRuleVO.getThresholdId())) {

                //阈值
                Threshold threshold = Threshold.builder()
                        .ruleId(salesRuleVO.getRuleId())
                        .thresholdId(salesRuleVO.getThresholdId())
                        .thresholdName(String.format("%s-派单客单价阈值", salesRuleVO.getOrgThrName()))
                        .type(0)
                        .thresholdParam(String.valueOf(salesRuleVO.getEventId()))
                        .thresholdValue(JSONObject.toJSONString(salesRuleVO))
                        .expression(ThresholdExpressionEnum.ALL.getExpression())
                        .creater(super.getMcStaffRealName())
                        .updater(super.getMcStaffRealName())
                        .updateTime(now)
                        .createTime(now)
                        .build();
                flag.updateAndGet(v -> v + thresholdService.insert(threshold));

                if (flag.get() > 0) {
                    alarmRuleBService.cacheRule(uniqueNo, salesRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            //修改
            else {

                Threshold threshold = thresholdService.findById(salesRuleVO.getThresholdId());
                SalesRuleVO vo = JSONObject.parseObject(threshold.getThresholdValue(), SalesRuleVO.class);
                //获取上次rediskey
                String oldRedisKey = vo.getUniqueNo();
                vo.setOrgThrId(salesRuleVO.getOrgThrId());
                vo.setOrgThrName(salesRuleVO.getOrgThrName());
                vo.setPlat(salesRuleVO.getPlat());
                vo.setPlatName(salesRuleVO.getPlatName());
                vo.setExpression(salesRuleVO.getExpression());
                vo.setValue(salesRuleVO.getValue());
                vo.setReceiverId(salesRuleVO.getReceiverId());
                vo.setReceiverName(salesRuleVO.getReceiverName());
                vo.setUniqueNo(salesRuleVO.getUniqueNo());
                //添加钉钉群支持
                vo.setRobotId(salesRuleVO.getRobotId());
                vo.setGroupName(salesRuleVO.getGroupName());
                threshold.setThresholdName(String.format("%s-派单客单价阈值", salesRuleVO.getOrgThrName()));
                threshold.setThresholdValue(JSONObject.toJSONString(vo));
                threshold.setUpdateTime(now);
                threshold.setUpdater(super.getMcStaffRealName());

                flag.updateAndGet(v -> v + thresholdService.updateByKey(threshold));

                if (flag.get() > 0) {
                    alarmRuleBService.cacheRule(uniqueNo, oldRedisKey, salesRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            if (flag.get() > 0) {
                return ResponseDTO.success();
            }
        } catch (Exception e) {
            logger.error("保存派单客单价规则配置异常，异常信息：" + e);
            e.printStackTrace();
        }
        return ResponseDTO.fail("保存派单客单价规则配置失败");
    }


}
